var exp = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var fs = require('fs');
var multer = require('multer');


var app = exp();
app.use(exp.static('www'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser());
// ********************注册页面**********************
app.post('/register', (req,res)=>{
    req.body.ip = req.ip;
    req.body.time = new Date();

    function send(code,message) {
        res.json({code,message});
    }
    function saveFile() {
        var filename = `users/${req.body.petname}.txt`;

        fs.exists(filename, function(exists){
            if (exists) {
                send('registered','该用户名被占用');
            }else{
                send('success','注册成功！！！')
            }
        });
    }
    fs.exists('users',function (exists) {
        if (exists){
            saveFile();
        }else{
            fs.mkdirSync('users',function (err) {
                if (err) {
                    send('file error','创建文件失败!!!');
                } else {
                    console.log('创建成功')
                }
            });
            saveFile();
        }
    });
});

// **************************登录*************************************
app.post('signin',(req,res)=>{
    var filename = `users/${req.body.petname}.txt`;

    function send(code,message) {
        res.json({code,message});
    }

    fs.exists(filename,function (exists) {
        if (exists) {
            fs.readFile(filename,function (err,data) {
                if (err) {
                    send('file error', '读取错误');
                }else{
                    var user = JSON.parse(data);
                    if (user.password == req.body.password) {
                        res.cookie('petname',req.body.petname);
                        send('success','登录成功');
                    }else{
                        send('signin error','密码错误')
                    }
                }
            });
        }else{
            send('register error','该用户未注册');
        }
    })
});
//*********************************提问*************************** */
app.post('/ask', (req, res)=>{
    var petname = req.cookies.petname;
    if (!petname) {
        send('signin error', '请重新登录...');
        return;
    }

    function send(code, message) {
        res.json({code, message});
    }

    var time = new Date();
    req.body.petname = petname;
    req.body.ip = req.ip;
    req.body.time = time;
    console.log(req.body);

    function saveFile() {
        var filename = `questions/${time.getTime()}.txt`;

        fs.appendFile(filename, JSON.stringify(req.body), function(err){
            if (err) {
                send('file error', '抱歉，系统错误...');
            } else {
                send('success', '问题提交成功！');
            }
        });
    }

    fs.exists('questions', function(exists){
        if (exists) {
            saveFile();
        } else {
            fs.mkdir('questions', function(err){
                if (err) {
                    send('file error', '抱歉，系统错误...');
                } else {
                    saveFile();
                }
            });
        }
    });
});
//****************************回答*********** */
app.post('/answer', (req, res)=>{
    var petname = req.cookies.petname;

    function send(code, message) {
        res.json({code, message});
    }

    if (!petname) {
        send('signin error', '请重新登录...');
        return;
    }
    console.log(req.body);
    var filename = `questions/${req.body.question}.txt`;
    console.log(filename);

    req.body.petname = petname;
    req.body.ip = req.ip;
    req.body.time = new Date();

    fs.readFile(filename, (err, data)=>{
        if (err) {
            send('file error', '抱歉，系统错误...');
        } else {
            var question = JSON.parse(data);
            if (!question.answers) {
                question.answers = [];
            }

            question.answers.push(req.body);

            fs.writeFile(filename, JSON.stringify(question), function(err){
                if (err) {
                    send('file error', '抱歉，系统错误...');
                } else {
                    send('success', '回答提交成功！');
                }
            });
        }
    });
});

// ===============首页================
app.get('/questions', (req, res)=>{
    function send(code, message, data) {
        res.json({code, message, data});
    }

    function readFiles(i, files, questions, complete) {
        if (i < files.length) {
            console.log(`questions/${files[i]}`);
            fs.readFile(`questions/${files[i]}`, function(err,data){
                if (!err) {
                    questions.push(JSON.parse(data));
                }
                readFiles(++i, files, questions, complete);
            });
        } else {
            complete();
        }
    }

    fs.readdir('questions', (err, files)=>{
        if (err) {
            send('file error', '抱歉，系统错误...');
        } else {
            console.log(files);
            files = files.reverse();
            var questions = [];
            readFiles(0, files, questions, function(){
                send('success', '读取数据成功！', questions);
            });
        }
    });
});
//*************************头像****************************** */
app.get('/user/photo', sign, (req, res) => {
    res.render('user/photo.html', {
        title: '修改头像'
    })
})
app.post('/user/photo', sign, uploads.single('photo'), (req, res) => {
    res.status(200).json({ code: 'success', message: '上传成功' })
})
app.listen(3001,()=>{console.log('服务器启动成功');});